import axios, { AxiosError, AxiosRequestConfig, AxiosResponse } from 'axios'
import { Toast } from 'vant'
import router from '@/router/index'

const request = axios.create({
  baseURL: '/api/', // https://music-serve-two.vercel.app/
  withCredentials: true,
})

// 请求拦截器
request.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    config.params = Object.assign({}, config.params, {
      realIP: '116.25.146.177',
    })
    console.log(config, 3)
    return config
  },
  (error: AxiosError) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  (response: AxiosResponse) => {
    if (response.data.code !== 200) {
      Toast(response.data.message)
    }
    return response
  },
  (error: AxiosError) => {
    // 未登录
    if (error.response?.status === 301) {
      router.push('/login')
    }
    return Promise.reject(error)
  }
)

export default request
